const path = require('path');
const fs = require('fs');
const webpack = require('webpack');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const ModuleIds = require('./moduleIds')


function resolve(dir) {
  return path.join(__dirname, dir)
}


const externals = {
  'vue': 'Vue',
  'element-ui': 'ElementUI',
  'element-ui': 'ELEMENT',
  'jquery': '$',
  // '@/store/index': '../store/index',
  // '@/common/CuPopover': '../common/CuPopover',
  // '@/common/CustomPage': '../common/CustomPage',
  // '@/common/DynamicTable': '../common/DynamicTable',
  // '@/common/TreeSelect': '../common/TreeSelect',
  // '@/common/CuDatepicker': '../common/CuDatepicker',
  // '@/common/UploadDialog': '../common/UploadDialog',
  // '@/util/dictionaryCode': '../common/DictionaryCode',
  // '@/util/customRules': '../util/customRules',
  // '@/util/filter': '../utilFilter',
  // '@/lib/request': '../lib/request',
  // '@/lib/public-method': '../lib/PublicMethod',
  // '@/lib/water-marker': '../lib/WaterMarker',
};
const commonPath = resolve('src/common');
const libPath = resolve('src/lib');
const utilPath = resolve('src/util');

const projectPath = path.join(__dirname, 'src/');
function explorer(cPath, prefix) {
  var readDirs = fs.readdirSync(cPath);
  console.info('--------------------------');
  readDirs.forEach(function(fileName) {
    var fullPath = cPath + '/' + fileName;

    if (fs.statSync(fullPath).isDirectory()) {
      console.info('读取文件夹：' + fullPath);
      explorer(fullPath, prefix);
    } else {
      console.info('读取文件：' + fullPath);
      // 读出所有的文件
      var fileNames = fullPath.replaceAll(projectPath, prefix).split('.');
      let commonFileAlias =fileNames[0];
      externals[commonFileAlias] = commonFileAlias;
    }
  })
}

explorer(commonPath, '@/');
explorer(libPath, '@/');
explorer(utilPath, '@/');

console.info('过滤引用文件:', externals);

const name = 'module'; // page title
module.exports = {
  publicPath: './', // 根域上下文目录
  outputDir: 'dist', // 构建输出目录
  assetsDir: 'assets', // 静态资源目录 (js, css, img, fonts)
  lintOnSave: false, // 是否开启eslint保存检测，有效值:ture | false | 'error'
  runtimeCompiler: true, // 运行时版本是否需要编译
  transpileDependencies: [], // 默认babel-loader忽略mode_modules，这里可增加例外的依赖包名
  productionSourceMap: true, // 是否在构建生产包时生成 sourceMap 文件，false将提高构建速度
  configureWebpack: config => {
    return {
      name,
      entry: './src/main.js',
      resolve: {
        alias: {
          '@': resolve('src')
        }
      },
      plugins: [
        new ModuleIds(),
        // new webpack.ProvidePlugin({
        //   $: 'jquery',
        //   jQuery: 'jquery',
        //   'windows.jQuery': 'jquery'
        // }),
        // new UglifyJsPlugin({
        //   uglifyOptions: {
        //     compress: false
        //   }
        // })
        // new BundleAnalyzerPlugin()
      ],
      devtool: 'source-map',
      optimization: {
        splitChunks: {
          chunks: 'async',
          maxAsyncRequests: 20,
          maxInitialRequests: 10,
          minSize: 0,
          minChunks: 1,
          cacheGroups: {
            Vue: {
              name: 'vue',
              test: /[\\/]node_modules[\\/]vue[\\/]/,
              priority: -10
            },
            Vuex: {
              name: 'vue',
              test: /[\\/]node_modules[\\/]vuex[\\/]/,
              priority: -10
            },
            // libs: {
            //   // name: 'chunk-libs',
            //   name(module) {
            //     const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1]
            //     // npm package names are URL-safe, but some servers don't like @ symbols
            //     return `npm.${packageName.replace('@', '')}`
            //   },
            //   test: /[\\/]node_modules[\\/]/,
            //   priority: 10,
            //   reuseExistingChunk: true,
            //   chunks: 'initial'
            // },
            elementUI: {
              name: 'chunk-elementUI', // 拆分elementUI为单个包
              priority: 20, // 权重需要大于libs和app，否则将打包成libs或app
              test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // 兼容cnpm
            },
            'common': {
              name: 'common',
              test: /[\\/]src[\\/]common/,
              priority: -11
            },
            'util': {
              name: 'util',
              test: /[\\/]src[\\/]util/,
              priority: -11
            },
            'lib': {
              name: 'lib',
              test: /[\\/]src[\\/]lib/,
              priority: -11
            },
            'store': {
              name: 'store',
              test: /[\\/]src[\\/]store/,
              priority: -10
            },
            // 'element-ui': {
            //   name: 'element-ui',
            //   test: /[\\/]node_modules[\\/]element-ui[\\/]/,
            //   priority: -20
            // },
            // 'vendors': {
            //   name: 'vendors',
            //   test: /[\\/]node_modules[\\/]/,
            //   priority: -20
            // }
          }
        }
      }
    }
  },
  chainWebpack: (config) => {
    if (process.env.NODE_ENV !== 'development')
      config.set('externals', externals);


    // 需要定义根目录变量方便打包后内部引用路径出错
    config.resolve.alias.set('@', path.resolve('src'));
    // 必须配置图片转为base64，否则图片路径无法引入
    config.module
      .rule('images')
      .test(/\.(png|jpg|gif)$/)
      .use('url-loader')
      .loader('url-loader')
      .tap(options => Object.assign(options, { limit: 1 * 1024 * 1024 }))
  },
  parallel: require('os').cpus().length > 1, // 构建时开启多进程处理babel编译
  pluginOptions: {
    // 第三方插件配置
  },
  devServer: {
    open: true,
    host: '0.0.0.0',
    port: 8080,
    https: false,
    hotOnly: false,
    proxy: {
      // 配置跨域
      [process.env.VUE_APP_BASE_API]: {
        target: 'http://192.168.22.105:8094',
        // target: 'https://192.168.17.151',
        ws: true,
        changOrigin: true,
        logLevel: 'debug',
        secure: false,
        pathRewrite: { // 重写路径
          ['^' + process.env.VUE_APP_BASE_API]: '/vmpro'
        }
      }
    }
  }
};
